package be.ipl.finito.servlets;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.ejb.EJB;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import be.ipl.finito.domaine.Joueur;
import be.ipl.finito.domaine.Partie;
import be.ipl.finito.usecases.GestionPartie;
import be.ipl.finito.utilitaires.ListeParties;

/**
 * Servlet implementation class Menu
 */
@WebServlet(name = "servletMenu.html")
public class Menu extends HttpServlet
{
	private static final long serialVersionUID = 1L;

	@EJB
	GestionPartie gestionPartie;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	@Override
	protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException
	{
		response.sendRedirect("menu.html");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	@Override
	protected void doPost(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException
	{
		final ServletContext context = getServletContext();

		final String selectionRecherche = request.getParameter("filtre");

		if (selectionRecherche == null || selectionRecherche.isEmpty()) {
			response.sendRedirect("menu.html?messageError=Votre recherche est incorrect");
			return;
		}

		List<Partie> parties = new ArrayList<Partie>();

		if (selectionRecherche.equals("attente")) {
			ListeParties mapPartiesEnAttente = (ListeParties) context.getAttribute("partiesEnAttente");

			if (mapPartiesEnAttente == null) {
				mapPartiesEnAttente = new ListeParties();
				synchronized (context) {
					context.setAttribute("partiesEnAttente", mapPartiesEnAttente);
				}
			}
			final List<Partie> tmp_parties = new ArrayList<Partie>(mapPartiesEnAttente.keySet());
			for (final Partie partie : tmp_parties) {
				if (!partie.estEnCours())
					parties.add(partie);
			}

		} else if (selectionRecherche.equals("suspendu")) {
			final HttpSession httpSession = request.getSession();

			final Joueur joueur = (Joueur) httpSession.getAttribute("joueur");
			parties = gestionPartie.listerPartieEnCours(joueur.getId());
		}

		request.setAttribute("listeParties", parties);
		request.setAttribute("valeurFiltre", selectionRecherche);
		this.getServletContext().getNamedDispatcher("menu.html").forward(request, response);
	}
}
